//
//  WXLogin.swift
//  E-CycleForShop
//
//  Created by enghou on 17/3/13.
//  Copyright © 2017年 xyxorigation. All rights reserved.
//

import UIKit

protocol inresponse {
    func response(urls : String) -> Void
    func errorOccur(response : SendAuthResp) -> Void
}

class WXLogin: NSObject,WXApiManagerDelegate {
    var delegate : inresponse?
    override init() {
        super.init()
    }
    func load(viewCtl : BaseViewController,scope : String,state : String,openid : String,delet : inresponse?)->Void {
        let req = SendAuthReq.init()
        req.scope = scope
        req.state = state
        req.openID = openid
        let manager = WXApiManager.shared()
        manager?.delegate = self
        delegate = delet
        if WXApi.isWXAppInstalled() == true {
            if WXApi.isWXAppSupport() == true {
                let _ = WXApi.sendAuthReq(req, viewController: viewCtl, delegate: manager)
                return
            }
        }
        viewCtl.commonAlertMsg(content: "尚未安装微信!")
    }
    //收到认证请求的回应
    func managerDidRecvAuthResponse(_ response: SendAuthResp!) {
        if response.errCode == 0 {
            let url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WXAPIKey + "&secret=" + WXAPISecret + "&code=" + response.code + "&grant_type=authorization_code"
            let request = URL.init(string: url)!
            let session = URLSession.shared
            let task = session.dataTask(with: request, completionHandler: {(data,response,error) in
                do{
                    let dic = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableLeaves) as? Dictionary<String,Any>
//                    print(dic)
                    if let token = dic?["access_token"] as? String{
                        if let openid = dic?["openid"] as? String{
                            let urls = "https://api.weixin.qq.com/sns/userinfo?access_token=" + token + "&openid=" + openid
                            self.delegate?.response(urls: urls)
                        }
                    }else {
                        self.delegate?.response(urls: "")
                    }
                    
                }catch{
                    
                }
            })
            task.resume()
        }else{
            self.delegate?.errorOccur(response: response)
        }
    }
    
    func managerDidRecvLaunch(_ request: LaunchFromWXReq!) {
        print("从微信启动")
    }
}
